#include "tmmysqlctrl.h"

TMMySQLCtrl::TMMySQLCtrl(QObject *parent) : QObject(parent)
{
}

bool TMMySQLCtrl::connect_mysql(QString m_strIp)
{
    pr_dbMysql = QSqlDatabase::addDatabase("QMYSQL");
    pr_dbMysql.setDatabaseName("db_robotnet");
    pr_dbMysql.setHostName(m_strIp);
    pr_dbMysql.setPort(3306);
    pr_dbMysql.setUserName("tami");
    pr_dbMysql.setPassword("Tami1234!");
    pr_dbMysql.setConnectOptions("MYSQL_OPT_CONNECT_TIMEOUT=3;");
    if (!pr_dbMysql.open()) {
        qDebug() << "Connect to MySql error: "<< pr_dbMysql.lastError().text();
        return false;
    }
    QSqlQuery query(pr_dbMysql);
    query.exec("SELECT 1;");
    if(query.size()>0){
        return true;
    }
    return false;
}

int TMMySQLCtrl::getPortByRobotMac(QString strMac)
{
    QString strSQL = QString("SELECT _id FROM t_robot WHERE mac='%1';").arg(strMac);
    QSqlQuery query(pr_dbMysql);
    query.exec(strSQL);
    if(query.size()<1){
        QString strSQL = QString("INSERT t_robot SET mac='%1';").arg(strMac);
        QSqlQuery query(pr_dbMysql);
        query.exec(strSQL);

        strSQL = QString("SELECT _id FROM t_robot WHERE mac='%1';").arg(strMac);
        query.exec(strSQL);
        query.next();
        return query.value(0).toInt();
    }
    query.next();
    return query.value(0).toInt();
}




